<?php

namespace App\Http\Controllers\home;

use Illuminate\Http\Request;
use Gregwar\Captcha\CaptchaBuilder;
use App\Http\Requests;
use App\Http\Requests\UserHomeRequest;
use App\Http\Controllers\Controller;
use Hash;
use DB;
use Mail;


class LoginController extends Controller
{
    /*
		前台注册
    */
	public function getRegist()
	{
		//解析模板
		return view('home.login.regist');
	}

	/*
		执行注册
	*/
	public function postDoregist(UserHomeRequest $request)
	{
		//处理数据
		$data = $request->except('_token','vcode','pcode');
		//验证码是否正确
		if($request->input('vcode') != session('Vcode')){
			return back()->with('error','验证码不正确');
		}
		//验证用户名/手机号是否存在
		$user = DB::table('shop_users')->where('uname',$data['uname'])->first();
		$tel = DB::table('shop_users')->where('tel',$data['uname'])->first();
		if($user){
			return back()->with('error','用户已存在');
		}
		if($tel){
			return back()->with('error','用户已存在');
		}
		//处理数据
		$data['upwd'] = Hash::make($data['upwd']);
		$data['token'] = str_random(50);
		$data['regtime'] = time();
		//添加数据并获取id
		$res = DB::table('shop_users')->insertGetId($data);
		if($res){
			return view('/home/index/index');
		}else{
			return back()->with('error','注册失败，请联系客服');
		}
		
	}


	/*
		验证码方法
	*/
	public function getVcode()
	{
		ob_clean();//清除输出缓存区的内容
	    //生成验证码图片的Builder对象，配置相应属性
	    $builder = new CaptchaBuilder;
	    //可以设置图片宽高及字体
	    $builder->build($width = 100, $height = 40, $font = null);
	    //获取验证码的内容
	    $phrase = $builder->getPhrase();

	    //把内容存入session
	    session(['Vcode'=>$phrase]);
	    //生成图片
	    header("Cache-Control: no-cache, must-revalidate");
	    header('Content-Type: image/jpeg');
	    $builder->output();

	}

	/*
		接受ajax请求 发送验证码
	*/
	public function getSendcode(Request $request)
	{
		//获取手机号
		$tel = $request->input('tel');
		//建立随机6位验证码
		$rand = rand(000000,999999);
		session(['Pcode'=>$rand]);
		//初始化必填
		$options['accountsid']='26451e47b0c70774e9d8385f4f62dfe8';
		$options['token']='c97798746c3400379ed03b3bd36ec7ce';


		//初始化 $options必填
		$ucpass = new \Ucpaas($options);
		//开发者账号信息查询默认为json或xml
		  // $ucpass->getDevinfo('json');

		//短信验证码（模板短信）,默认以65个汉字（同65个英文）为一条（可容纳字数受您应用名称占用字符影响），超过长度短信平台将会自动分割为多条发送。分割后的多条短信将按照具体占用条数计费。
		$appId = "0eb082d518ad42c6baeed34cd26df2c4";
		$to = $tel;
		$templateId = "35333";
		$param="好乐买,{$rand},3";

		$ucpass->templateSMS($appId,$to,$templateId,$param);
	}	

	/*
		验证手机验证码是否正确
	*/
	public function getPcode(Request $request)
	{
		if(empty($request->input('pcode'))){
					echo 0;
		}else if($request->input('pcode') == session('Pcode')){
				echo 1;	
		}
		
	}

	/*
		验证图片验证码是否正确
	*/
	public function getCode(Request $request)
	{
		//验证码是否正确
		if($request->input('vcode') == session('Vcode')){
			echo 1;
		}
	}

	/*
		用户名是否存在验证
	*/
	public function getIsuser(Request $request)
	{
		$uname = $request->input('uname');
		//查询数据库
		$res = DB::table('shop_users')->where('uname',$uname)->first();
		if($res){
			echo 1;
		}else{
			echo 0;
		}
	}

	/*
		手机号是否存在验证
	*/
	public function getIsphone(Request $request)
	{
		$tel = $request->input('tel');
		//查询数据库
		$res = DB::table('shop_users')->where('tel',$tel)->first();
		if($res){
			echo 1;
		}else{
			echo 0;
		}
	}

	/*
		登录
	*/
	public function getLogin()
	{
		//解析模板
		return view('home.login.index');
	}

	/*
		执行登录
	*/
	public function postDologin(Request $request)
	{	
		$data = $request->except('_token');
		//用户名非空判断
		if(empty($data['uname'])){
			return back()->with('error','用户名不能为空');
		}
		//密码非空判断
		if(empty($data['upwd'])){
			return back()->with('error','密码不能为空');
		}
		//判断用户名/邮箱/手机号是否唯一
		$users = DB::table('shop_users')->where('uname',$data['uname'])->first();
		$tel = DB::table('shop_users')->where('tel',$data['uname'])->first();
		$email = DB::table('shop_users')->where('email',$data['uname'])->first();

		if($users){
			//判断密码是否正确
			$pw = Hash::check($request->input('upwd'),$users->upwd);
			if($pw){
				//将用户信息写入session
				session(['uid'=>$users->uid,'uname'=>$users->uname]);
				return redirect('/')->with('success');
			}else{
				return back()->with('error','用户密码不正确');
			}
			
		}else if($tel){
			//判断密码是否正确
			$pww = Hash::check($request->input('upwd'),$tel->upwd);
			if($pww){
				//将用户信息写入session
				session(['uid'=>$tel->uid,'uname'=>$tel->uname]);
				return redirect('/')->with('success');
			}else{
				return back()->with('error','用户密码不正确');
			}
		}else if($email){
			//判断密码是否正确
			$pwww = Hash::check($request->input('upwd'),$email->upwd);
			if($pwww){
				//将用户信息写入session
				session(['uid'=>$email->uid,'uname'=>$email->uname]);
				return redirect('/')->with('success');
			}else{
				return back()->with('error','用户密码不正确');
			}
		}else{
			 return back()->with('error','用户不存在');
		}
		
	}

	/*
		密码找回
	*/
	public function getFgtpw()
	{
		//解析模板
		return view('home.login.fgtpw');
	}	
	/*
		执行密码找回
	*/
	public function postFindpw(Request $request)
	{
		//处理数据
		$data = $request->except('_token'); 
		//用户名非空判断
		if(empty($data['account'])){
			return back()->with('error','手机名不能为空');
		}
		//验证码非空判断
		if(empty($data['validate'])){
			return back()->with('error','验证码不能为空');
		}
		//验证码是否正确
		if($request->input('validate') != session('Vcode')){
			return back()->with('error','验证码不正确');
		}
		$tel = DB::table('shop_users')->where('tel',$data['account'])->first();
		if($tel){
			//发验证码
			return view('home.login.sendmessage',['tel'=>$tel]);
		}else{
			return back()->with('error','手机号不存在');
		}
	}

	/*
		修改密码页
	*/
	public function postDoupw(Request $request)
	{
		$uid = $request->input('uid');
		return view('/home/login/doupw',['uid'=>$uid]);
	}

	/*
		修改密码方法
	*/
	public function postUpupw(Request $request)
	{

		$data = $request->except('_token');
	
		//非空以及格式判断
		if(empty($data['upw'])){
			// return back()->with('error','密码不能为空');
			return redirect('/')->with('error','密码不能为空');
		}
			
		if(!preg_match("/\w{6,18}/",$data['upw'])){
			// return back()->with('error','密码格式不正确');
			return redirect('/')->with('error','密码格式不正确');
		}
		if($data['upw'] != $data['reupw']){
			// return back()->with('error','两次输入密码不能为空');
			return redirect('/')->with('error','两次密码不一致');
		}

		//加密
		$data['upw'] = Hash::make($data['upw']);
		$arr = ['upwd'=>$data['upw']] ;
		$res = DB::table('shop_users')->where('uid', $request->input('uid'))->update($arr);
		if($res){
   			//成功
   			return redirect('/')->with('success','修改成功');
   		}else{
   			//失败
   			return redirect('/')->with('error','修改失败');

		}
	}

	/*
		用户退出
	*/ 
	public function getExit(Request $request)
	{
		$request->session()->flush();
		return redirect('/');
	}
}
